package com.zx.map.controller;

import com.zx.map.common.ManageCommonHelper;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.EncashLogService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.domain.EncashLogDownloadDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.EncashLogModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.mobile.domain.EncashQueryDomain;
import com.zx.platform.context.DirectoryInfoContext;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.report.ReportUtil;
import com.zx.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/manage/encashlog")
public class EncashLogController {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(EncashLogController.class);

    @Autowired
    private EncashLogService encashLogService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private MerchantInfoService merchantInfoService;

    /**
     * 取现列表	 *
     *
     * @param encashQueryDomain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/encashList")
    public String encashList(EncashQueryDomain encashQueryDomain, Model model,
                             HttpServletRequest request) {

        try {// 初始化信息
            Integer pageNum = encashQueryDomain.getPageNum();
            Integer pageSize = encashQueryDomain.getPageSize();
            Integer pageCount = encashQueryDomain.getPageCount();
            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = 10;
            }
            encashQueryDomain.setPageSize(pageSize);
            encashQueryDomain.setPageNum(pageNum);
            if (StringUtils.isBlank(encashQueryDomain.getBeginDate())) {
                encashQueryDomain.setBeginDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(encashQueryDomain.getEndDate())) {
                encashQueryDomain.setEndDate(PmpUtils.dateToString(new Date(),
                        "yyyy-MM-dd"));
            }
            // 查找当前操作员对应的代理商
            AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
            if(curAgentInfoModel!=null){
                curAgentInfoModel.setHasSelf(true);
            }
            Map map = encashLogService.getPageByDomain(curAgentInfoModel, encashQueryDomain);
            List<EncashLogModel> encashLogList = (List<EncashLogModel>) map.get("list");
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", encashLogList);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            double settleAmt = Double.valueOf(map.get("settleAmt").toString());
            model.addAttribute("settleAmt", settleAmt);
            model.addAttribute("model", encashQueryDomain);
            return "/jsp/map/ordLog/listAutoSettle";
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }
    /**
     * 代理商结算查询
     * @param encashQueryDomain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/agentQueryencash")
    public String agentQueryencash(EncashQueryDomain encashQueryDomain, Model model,
                             HttpServletRequest request) {

        try {// 初始化信息
            Integer pageNum = encashQueryDomain.getPageNum();
            Integer pageSize = encashQueryDomain.getPageSize();
            Integer pageCount = encashQueryDomain.getPageCount();
            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = 10;
            }
            encashQueryDomain.setPageSize(pageSize);
            encashQueryDomain.setPageNum(pageNum);
            if (StringUtils.isBlank(encashQueryDomain.getBeginDate())) {
                encashQueryDomain.setBeginDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(encashQueryDomain.getEndDate())) {
                encashQueryDomain.setEndDate(PmpUtils.dateToString(new Date(),
                        "yyyy-MM-dd"));
            }
            // 查找当前操作员对应的代理商
 			AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
            if(curAgentInfoModel!=null){
                curAgentInfoModel.setHasSelf(true);
            }
            Map map = encashLogService.getPageByDomain(curAgentInfoModel, encashQueryDomain);
            List<EncashLogModel> encashLogList = (List<EncashLogModel>) map.get("list");
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", encashLogList);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            double settleAmt = Double.valueOf(map.get("settleAmt").toString());
            model.addAttribute("settleAmt", settleAmt);
            model.addAttribute("model", encashQueryDomain);
            return "/jsp/map/ordLog/agentQueryencash";
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 取现下载	 *
     *
     * @param encashQueryDomain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/downLncashList")
    public String downLncashList(EncashQueryDomain encashQueryDomain, Model model,
                                 HttpServletRequest request, HttpServletResponse response) {

        try {
            if (StringUtils.isBlank(encashQueryDomain.getBeginDate())) {
                encashQueryDomain.setBeginDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(encashQueryDomain.getEndDate())) {
                encashQueryDomain.setEndDate(PmpUtils.dateToString(new Date(),
                        "yyyy-MM-dd"));
            }
            List<EncashLogModel> encashLogList = encashLogService.getListByDomainForManage(encashQueryDomain);
            List<EncashLogDownloadDomain> reportList = new ArrayList<EncashLogDownloadDomain>();
            for (EncashLogModel o : encashLogList) {
                //交易状态
                if (StringUtils.isNotBlank(o.getEncashStatus())) {
                    o.setEncashStatus(DirectoryInfoContext.getCaptionByKeyAndValue("2130", o.getEncashStatus()));
                }
                if (StringUtils.isNotBlank(o.getSettleStatus())) {
                    o.setSettleStatus(DirectoryInfoContext.getCaptionByKeyAndValue("2020", o.getSettleStatus()));
                }
                EncashLogDownloadDomain temp = new EncashLogDownloadDomain();
                BeanUtils.copyProperties(o, temp);
                //设置订单类型  商户名称 代理商名称
                MerchantInfoModel tempMer = merchantInfoService.getModelByKey(o.getMerchantId());
                AgentInfoModel tempAgent = agentInfoService.getAgentInfoModelBySysAccount(o.getAgentSysAccount());
                //System.out.println(o.getAgentSysAccount()+tempAgent);
                if(tempAgent!=null){
                	temp.setAgentName(tempAgent.getAgentName());
                }
                if(tempMer!=null){
                	temp.setMerName(tempMer.getMerchantName());
                }
                if (ManageCommonHelper.ENCASHTYPE_T0.equals(o.getEncashType())) {
                    temp.setEncashType("T0");
                } else if (ManageCommonHelper.ENCASHTYPE_T1.equals(o.getEncashType())) {
                    temp.setEncashType("T1");
                }
                reportList.add(temp);
            }
            Map<Integer, Object> formatAttr = new HashMap<Integer, Object>();
            formatAttr.put(1, ReportUtil.Date_cro);
            try {

                String[] header = null;
                header = new String[]{"创建时间", "交易流水号", "取现金额","取现类型","客户账户","商户名称","代理商账户","代理商名称",
                        "结算订单号","取现状态","结算金额","结算状态","结算备注"};
                String sts = ReportUtil.exportReport(header, reportList, null,
                        "取现查询", formatAttr, null, response);
                String[] st = sts.split("#");
                ReportUtil.download(response, st[0], st[1]);
            } catch (Exception e) {
                log.error("取现流水", e);
            }
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
        return null;
    }

}
